<?php
declare (strict_types=1);

namespace app\common\listener;
use app\common\model\BusinessFundsFlow as BusinessFundsFlowModel;
use app\common\model\OrderProduct;
use app\common\model\OrderRefund;

class BusinessFundsFlow
{
    public function handle($data): bool
    {
        try{
            $method = $data['type'];
            $this->$method($data['order']);
            return true;
        }catch (\Exception $e){
            return false;
        }

    }

    /**
     * 创建流水
     * @param $order
     * @return bool
     */
    private function add($order) :bool
    {
        $products = OrderProduct::where('order_id', $order->id)->column('concat_ws("/", title,sku_name) as title', 'spec_value_id');

        BusinessFundsFlowModel::create([
            'business_id' => $order->business_id,
            'type'        => 1,
            'order_id'    => $order->id,
            'order_sn'    => $order->sn,
            'deal_time'   => date("Y-m-d H:i:s", $order->getData('pay_time')),
            'amount'      => $order->real_amount,
            'real_amount' => $order->real_amount,
            'spec_value_ids' => implode(',', array_keys($products)),
            'sku_list'=> implode('，', array_column($products,'title'))
        ]);

        return true;
    }

    /**
     * 流水入账
     * @param $order
     * @return bool
     */
    private function entry($order) :bool
    {
        $refund_amount = OrderRefund::where('order_id', $order->id)->sum('total');

        $products = OrderProduct::where(['order_id' => $order->id, 'return_status'=>0])->column('concat_ws("/", title,sku_name) as title', 'spec_value_id');

        $flow = BusinessFundsFlowModel::where('order_id', $order->id)->find();
        $flow->real_amount = roundNum($order->real_amount - $refund_amount, 2);
        $flow->entry_time = date("Y-m-d H:i:s");
        $flow->status = 2;
        $flow->spec_value_ids = implode(',', array_keys($products));
        $flow->sku_list = implode('，', array_column($products,'title'));

        $flow->save();

        return true;
    }
}